package cc.sheji.Service;


import cc.sheji.domain.*;
import cc.sheji.reposity.JobRepository;
import cc.sheji.reposity.MyPhotoRepository;
import cc.sheji.util.QueryHelp;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
public class MyPhotoService {

    @Autowired
    MyPhotoRepository myPhotoRepository;
    @Autowired
    JobRepository jobRepository;

    public MyPhoto create(MyPhoto entity) {
        Long jobId = entity.getJobId();

        if (jobId != null) {
            Job job = jobRepository.findById(jobId).get();
            JSONArray finalResultImages = job.getFinalResultImages();
            if (finalResultImages != null)
                for (int i = 0; i < finalResultImages.size(); i++) {
                    MyPhoto entity1 = new MyPhoto();
                    entity1.setJobId(jobId);
                    entity1.setUserId(StpUtil.getLoginIdAsLong());
                    entity1.setPath(finalResultImages.getString(i));
                    entity1.setCmd(job.getCmd());
                    entity1.setModule(job.getModule());
                    entity1.setPictureWeight(job.getPictureWeight());
                    entity1.setStyle(job.getStyle());
                    entity1.setType(job.getType());
                    entity1.setProductMode(job.getProductMode());
                    entity1.setWidth2height(job.getWidth2height());
                    myPhotoRepository.save(entity1);
                }
            return entity;
        } else {
            entity.setUserId(StpUtil.getLoginIdAsLong());
            entity = myPhotoRepository.save(entity);
        }
        return entity;
    }

    public MyPhoto get(Long id) {
        MyPhoto entity = myPhotoRepository.findById(id).get();
        return entity;
    }

    public MyPhoto update(MyPhoto entity) {
        entity = myPhotoRepository.save(entity);
        return entity;
    }

    public List<MyPhoto> list(MyPhotoQueryCriteria criteria, Pageable pageable) {

        Sort order = Sort.by(Sort.Direction.ASC, "createTime");
        order = Sort.by(Sort.Direction.DESC, "createTime");
        pageable = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), order);
        Page<MyPhoto> page = myPhotoRepository.findAll((root, criteriaQuery, criteriaBuilder) ->
                QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return page.getContent();
    }
}
